package demo.view.scene
{
	import demo.controller.DemoController;
	import demo.events.DemoMapEvent;
	import demo.events.DemoPlayerEvent;
	import demo.model.DemoModel;
	import demo.model.SceneModel;
	import demo.view.player.DemoPlayerBase;
	import demo.vo.PlayerVO;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import helper.URLLoaderHelper;
	
	import map.MapAssetBase;
	import map.MapAssetLoader;
	import map.MapAssetVO;
	import map.MapEvent;
	import map.MapGridBase;
	import map.MapPoint3D;
	import map.MapRoadPoint;
	import map.MapSprite;
	import map.MapUtils;
	import map.MapViewBase;
	
	import mx.core.INavigatorContent;
	
	public class SceneView extends Sprite
	{
		private var _controller:DemoController;
		private var _model:DemoModel;
		private var _sceneModel:SceneModel;
		private var _mapConfig:XML;//场景地图配置文件
		private var _mapViewBase:MapViewBase;//地图资源物件
		private var _mapGridLayer:MapGridBase;//地图网格层
		private var _actionGridLayer:MapSprite;//玩家可行动的网格层
		private var _selfPlayer:DemoPlayerBase;//玩家自已
		private var _actionGridArray:Vector.<Object>=new Vector.<Object>();//玩家行动格子列表
		
		public function SceneView(controller:DemoController, model:DemoModel, sceneModel:SceneModel)
		{
			_controller=controller;
			_model=model;
			_sceneModel=sceneModel;
			setView();
			setEvent();
			_sceneModel.mapConfigPath="map/map.xml";//临时使用
		}
		
		private function setView():void
		{
			_actionGridLayer=new MapSprite();
			_actionGridLayer.mouseEnabled=false;
			addChild(_actionGridLayer);
			
			_mapViewBase=new MapViewBase();
			addChild(_mapViewBase);
			
			_mapGridLayer=new MapGridBase(_sceneModel.sceneVO.cellSize, _sceneModel.sceneVO.mapRow, _sceneModel.sceneVO.mapCols, 0x999999, 0.2);
			_mapGridLayer.alpha=0.0;
			addChild(_mapGridLayer);
		}
		
		private function setEvent():void
		{
			_mapGridLayer.addEventListener(MouseEvent.CLICK, __onMapClick);
			_sceneModel.addEventListener(DemoMapEvent.MAP_CONFIG_PATH_CHANGE, __onMapConfigPathChange);
			
			addEventListener(MouseEvent.MOUSE_DOWN, __onMouseDown);
			addEventListener(MouseEvent.MOUSE_UP, __onMouseUp);
		}
		
		private function removeEvent():void
		{
			_mapGridLayer.removeEventListener(MouseEvent.CLICK, __onMapClick);
			_sceneModel.removeEventListener(DemoMapEvent.MAP_CONFIG_PATH_CHANGE, __onMapConfigPathChange);
			if(_selfPlayer) _selfPlayer.removeEventListener(DemoPlayerEvent.PLAYER_POINT_CHANGE, __onSelfPlayerPointChange);
			if(_selfPlayer) _selfPlayer.removeEventListener(DemoPlayerEvent.PLAYER_GOTO_TARGET_POINT, __onPlayerGoToTargetPoint);
		}
		
		private function __onMouseDown(evt:MouseEvent):void
		{
			this.startDrag();
		}
		
		private function __onMouseUp(evt:MouseEvent):void
		{
			this.stopDrag();
		}		
		
		private function __onMapClick(evt:MouseEvent):void
		{
			var pt:Point=new Point(evt.localX, evt.localY);
			if(checkActionGridIsMove(MapUtils.getGridPoint(MapUtils.screenToSpace(pt), _sceneModel.sceneVO.cellSize))) _selfPlayer.playerVO.targetPoint=pt;
		}
		
		/**
		 *检查移动的目标点是否所属于行动格 
		 */		
		private function checkActionGridIsMove(pt:MapPoint3D):Boolean
		{
			for(var i:int=0;i<_actionGridArray.length;i++)
			{
				var gridPoint:MapPoint3D=_actionGridArray[i].gridPoint as MapPoint3D;
				if(gridPoint.x==pt.x && gridPoint.z==pt.z) return true;
			}
			return false;
		}
		
		/**
		 *当场景地图配置文件发生改变 
		 */
		private function __onMapConfigPathChange(evt:DemoMapEvent):void
		{
			var urlLoader:URLLoaderHelper=new URLLoaderHelper(_sceneModel.mapConfigPath, 0, loadMapConfig);
			urlLoader.loadSync();
		}
		
		/**
		 *成功加载场景地图配置 
		 */		
		private function loadMapConfig(data:*):void
		{
			_mapConfig=new XML(data);
			
			//取得地图基本信息
			_sceneModel.sceneVO.mapName=_mapConfig.name;
			_sceneModel.sceneVO.mapDescription=_mapConfig.description;
			_sceneModel.sceneVO.mapBackgroundPath=_mapConfig.background;
			_sceneModel.sceneVO.mapRow=_mapConfig.row;
			_sceneModel.sceneVO.mapCols=_mapConfig.cols;
			_sceneModel.sceneVO.cellSize=_mapConfig.size;
			
			var roadList:Array=_mapConfig.map.road.toString().split(',');
			for(var i:int=0;i<_sceneModel.sceneVO.mapRow;i++)
			{
				_sceneModel.sceneVO.roadArray[i]=[];
				for(var c:int=0;c<_sceneModel.sceneVO.mapCols;c++)
				{
					_sceneModel.sceneVO.roadArray[i][c]=roadList[0];
					roadList.shift();
				}
			}
			
			var assetXml:XML=XML(_mapConfig.map.asset);//取得物件列表
			
			//清除原资源物件库数据
			while(_sceneModel.sceneVO.assetLibPath.length>0)
			{
				_sceneModel.sceneVO.assetLibPath[0]=null;
				_sceneModel.sceneVO.assetLibPath.shift();
			}
			
			//设置资源库信息
			var arrLib:Array=assetXml.@assetLibPath.toString().split(',');
			for(var l:int=0;l<arrLib.length;l++)
			{
				var objLib:Object=new Object();
				objLib.isLoad=false;//标识当前库是未加载的
				objLib.path=arrLib[l];//指定库路径
				_sceneModel.sceneVO.assetLibPath.push(objLib);
			}
			
			//清除原物件数据
			while(_sceneModel.sceneVO.assetArray.length>0)
			{
				_sceneModel.sceneVO.assetArray[0]=null;
				_sceneModel.sceneVO.assetArray.shift();
			}
			
			//设置物件数据
			var arrAsset:XMLList=assetXml.item;
			if(arrAsset && arrAsset.length()>0)
			{
				for(var x:int=0;x<arrAsset.length();x++)
				{
					var mapAssetVO:MapAssetVO=new MapAssetVO();
					mapAssetVO.assetName=arrAsset[x].@assetName;
					mapAssetVO.isBottom=arrAsset[x].@isBottom=="true";
					mapAssetVO.isFloor=arrAsset[x].@isFloor=="true";
					mapAssetVO.isGrid=arrAsset[x].@isGrid=="true";
					mapAssetVO.isMirror=arrAsset[x].@isMirror=="true";
					mapAssetVO.link=arrAsset[x].@link;
					mapAssetVO.point=new MapPoint3D(arrAsset[x].@x, arrAsset[x].@y, arrAsset[x].@z);
					mapAssetVO.width=arrAsset[x].@width;
					mapAssetVO.height=arrAsset[x].@height;
					_sceneModel.sceneVO.assetArray.push(mapAssetVO);
				}
			}
			
			loadMapAssetLib();

			//更新网格
			_mapGridLayer.rowSize=_sceneModel.sceneVO.mapRow;
			_mapGridLayer.colsSize=_sceneModel.sceneVO.mapCols;
			_mapGridLayer.cellSize=_sceneModel.sceneVO.cellSize;
			_mapGridLayer.update();
		}
		
		/**
		 *加载地图资源物件库 
		 */		
		private function loadMapAssetLib():void
		{
			for each(var objLib:Object in _sceneModel.sceneVO.assetLibPath)
			{
				//加载资源库
				var mapAssetLoader:MapAssetLoader=new MapAssetLoader();
				mapAssetLoader.addEventListener(MapEvent.MAP_ASSET_LIB_LOAD_COMPLETE, __onMapAssetLibLoadComplete);
				mapAssetLoader.loadLib(objLib.path);
			}
		}
		
		/**
		 * 加载一个地图资源物件库完成
		 */		
		private function __onMapAssetLibLoadComplete(evt:MapEvent):void
		{
			var mapAssetLoader:MapAssetLoader=evt.currentTarget as MapAssetLoader;
			mapAssetLoader.removeEventListener(MapEvent.MAP_ASSET_LIB_LOAD_COMPLETE, __onMapAssetLibLoadComplete);
			setAssetLibPathLoadCompleteByPath(mapAssetLoader.path);
			mapAssetLoader.dispose();
			mapAssetLoader=null;
			
			if(checkAssetLibAllLoad())
			{//如果全部库资源已加载完成
				updateMapAsset();
			}
		}
		
		/**
		 *更新地图资源物件 
		 */		
		public function updateMapAsset():void
		{
			_mapViewBase.clearAll();
			
			//临时使用创建自已
			var playerVO:PlayerVO=new PlayerVO();
			playerVO.playerName="Devin";
			_selfPlayer=new DemoPlayerBase(playerVO, _sceneModel.sceneVO.roadArray, _sceneModel.sceneVO.cellSize);
			_selfPlayer.addEventListener(DemoPlayerEvent.PLAYER_POINT_CHANGE, __onSelfPlayerPointChange);
			_selfPlayer.addEventListener(DemoPlayerEvent.PLAYER_GOTO_TARGET_POINT, __onPlayerGoToTargetPoint);
			_selfPlayer.position=new MapPoint3D(80, 0, 80);
			_mapViewBase.addPlayer(_selfPlayer);//增加玩家自已
			
			showPlayerMoveMapGrid(_selfPlayer.position);
			
			for each(var mapAssetVO:MapAssetVO in _sceneModel.sceneVO.assetArray)
			{
				var mapAssetBase:MapAssetBase=new MapAssetBase(mapAssetVO);
				if(mapAssetBase.mapAssetVO.isFloor)
				{
					_mapViewBase.addToFloor(mapAssetBase);
				}
				else
				{
					_mapViewBase.addToAsset(mapAssetBase);
				}
			}
			
			_mapViewBase.drawFloor();
			
			
		}
		
		/**
		 *根据资源库路径，设置其已加载完成 
		 */		
		private function setAssetLibPathLoadCompleteByPath(path:String):void
		{
			for(var i:int=0;i<_sceneModel.sceneVO.assetLibPath.length;i++)
			{
				if(_sceneModel.sceneVO.assetLibPath[i].path==path)
				{
					_sceneModel.sceneVO.assetLibPath[i].isLoad=true;
				}
			}
		}
		
		/**
		 *检查库路径是否已经全部加载完成 
		 */		
		private function checkAssetLibAllLoad():Boolean
		{
			for(var i:int=0;i<_sceneModel.sceneVO.assetLibPath.length;i++)
			{
				if(_sceneModel.sceneVO.assetLibPath[i].isLoad==false) return false;
			}
			return true;
		}
		
		/**
		 *当前玩家自已坐标改变 
		 */		
		private function __onSelfPlayerPointChange(evt:DemoPlayerEvent):void
		{
			setCenter();
			_mapViewBase.depthSort();
		}
		
		/**
		 *当前玩家已行动至目标坐标点 
		 */		
		private function __onPlayerGoToTargetPoint(evt:DemoPlayerEvent):void
		{
			showPlayerMoveMapGrid((evt.currentTarget as DemoPlayerBase).position);
		}
		
		/**
		 *显示玩家可移动的地图格子 
		 */
		private function showPlayerMoveMapGrid(pt:MapPoint3D):void
		{
			clearActionGrid();
			var curGridPoint:MapPoint3D=MapUtils.getGridPoint(pt, _sceneModel.sceneVO.cellSize);
			
			for(var x:int=curGridPoint.x-_model.systemConfigVO.MaxMoveCellSize;x<=curGridPoint.x+_model.systemConfigVO.MaxMoveCellSize;x++)
			{
				for(var z:int=curGridPoint.z-_model.systemConfigVO.MaxMoveCellSize;z<=curGridPoint.z+_model.systemConfigVO.MaxMoveCellSize;z++)
				{
					if(x<0 || z<0 || x>=_sceneModel.sceneVO.mapRow || z>=_sceneModel.sceneVO.mapCols) continue;
					
					if(_sceneModel.sceneVO.roadArray[x][z]!=1)
					{//如果当前格不为障碍点
						var obj:Object=new Object();
						obj.gridPoint=new MapPoint3D(x, 0, z);
						var mapRoadPoint:MapRoadPoint=new MapRoadPoint(new MapPoint3D(x*_sceneModel.sceneVO.cellSize, 0, z*_sceneModel.sceneVO.cellSize), _sceneModel.sceneVO.cellSize, 0xffd9d9, 1);
						obj.roadPoint=mapRoadPoint;
						_actionGridArray.push(obj);
						_actionGridLayer.addChild(mapRoadPoint);
					}
				}
			}
		}
		
		/**
		 * 地图居中
		 */		
		private function setCenter():void
		{
			return;
			
			var xf : Number = -(_selfPlayer.x - stage.stageWidth / 2);
			var yf : Number = -(_selfPlayer.y - stage.stageHeight / 2)+50;
			
			if(xf > 0)xf = 0;
			if(xf < stage.stageWidth - _mapViewBase.width)
				xf = stage.stageWidth - _mapViewBase.width;
			if(yf > 0)yf = 0;
			if(yf < stage.stageHeight - _mapViewBase.height)
				yf = stage.stageHeight - _mapViewBase.height;
			
			if(xf>0) xf=0;
			if(yf>0) yf = 0;
			
			this.x = xf;
			this.y = yf;
		}
		
		/**
		 *清除玩家行动时可移动的格子 
		 */		
		private function clearActionGrid():void
		{
			while(_actionGridArray.length>0)
			{
				var mapRoadPoint:MapRoadPoint=_actionGridArray[0].roadPoint;
				if(mapRoadPoint.parent) mapRoadPoint.parent.removeChild(mapRoadPoint);
				mapRoadPoint.dispose();
				mapRoadPoint=null;
				_actionGridArray[0].gridPoint=null;
				_actionGridArray.shift();
			}
		}
		
		public function dispose():void
		{
			setEvent();
			clearActionGrid();
			_mapConfig=null;
			_actionGridArray=null;
			
			if(_selfPlayer)
			{
				if(_selfPlayer.parent) _selfPlayer.parent.removeChild(_selfPlayer);
				_selfPlayer.dispose();
			}
			_selfPlayer=null;			
			
			if(_mapViewBase)
			{
				if(_mapViewBase.parent) _mapViewBase.parent.removeChild(_mapViewBase);
				_mapViewBase.dispose();
			}
			_mapViewBase=null;
			
			if(_mapGridLayer)
			{
				if(_mapGridLayer.parent) _mapGridLayer.parent.removeChild(_mapGridLayer);
				_mapGridLayer.dispose();
			}
			_mapGridLayer=null;	
			
		}
	}
}